获取Python中的所有对象属性? 您所在的位置:网站首页 dom 获取所有attributes列表 获取Python中的所有对象属性?

获取Python中的所有对象属性?

2023-09-23 14:59| 来源: 网络整理| 查看: 265

本文翻译自:Get all object attributes in Python?

Is there a way to get all attributes/methods/fields/etc. 有没有一种方法来获取所有属性/方法/字段/等。 of an object in Python? Python中的对象?

vars() is close to what I want, but it doesn't work unless an object has a __dict__ , which isn't always true (eg it's not true for a list , a dict , etc.). vars() 接近我想要的,但是除非对象具有__dict__ ,否则它不起作用, __dict__并不总是正确的(例如,对于list , dict等不是正确的)。

#1楼

参考:https://stackoom.com/question/StUT/获取Python中的所有对象属性

#2楼

I use __dict__ 我用__dict__

Example : 范例 :

class MyObj(object): def __init__(self): self.name = 'Chuck Norris' self.phone = '+6661' obj = MyObj() print(obj.__dict__) # Output: # {'phone': '+6661', 'name': 'Chuck Norris'} #3楼

You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values 您可以使用dir(your_object)获取属性,并使用getattr(your_object, your_object_attr)获取值

usage : 用法:

for att in dir(your_object): print (att, getattr(your_object,att)) #4楼

使用内置函数dir() 。

#5楼

What you probably want is dir() . 您可能想要的是dir() 。

The catch is that classes are able to override the special __dir__ method, which causes dir() to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). 问题是类可以重写特殊的__dir__方法,这会导致dir()返回类所需的任何内容(尽管鼓励它们返回准确的列表,但未强制执行)。 Furthermore, some objects may implement dynamic attributes by overriding __getattr__ , may be RPC proxy objects, or may be instances of C-extension classes. 此外,某些对象可以通过覆盖__getattr__来实现动态属性,可以是RPC代理对象,或者可以是C扩展类的实例。 If your object is one these examples, they may not have a __dict__ or be able to provide a comprehensive list of attributes via __dir__ : many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it. 如果你的对象是一个这些例子,他们可能没有一个__dict__ 或能够提供通过属性的综合列表__dir__ :许多对象可以有这么多的动态ATTRS它不就不会真正知道它有什么 ,直到您尝试访问它。

In the short run, if dir() isn't sufficient, you could write a function which traverses __dict__ for an object, then __dict__ for all the classes in obj.__class__.__mro__ ; 从短期来看,如果dir()是不够的,你可以写一个横贯功能__dict__的对象,然后__dict__中的所有类obj.__class__.__mro__ ; though this will only work for normal python objects. 尽管这仅适用于普通的python对象。 In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has .feathers . 从长远来看,您可能必须使用鸭子输入+假设-如果它看起来像鸭子,请用手指交叉,并希望它具有.feathers 。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有